package com.base.myproject.client.HR.holiday;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.data.TreeModel;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.LabelField;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class YearVacationManager extends BaseJDBCPanel{
	private Button btnQuery = null;
	private DateField startDate = null;
	private DateField endDate = null;
	private BaseStore<BusiObject> store = null;
	private BaseGrid<BusiObject> grid=null;
	
	TextField<String> tx = new TextField<String> ();   //定义一个文本框输入查询条件
	private StoreFilterField<BusiObject> field;
	
	public YearVacationManager(){
		init();
	}
	
	public void complete() {
		super.complete();
		getToolbarll().add(new Label("人员查询："));
		getToolbarll().add(field);
	}
	
	public void init(){
		field = new StoreFilterField<BusiObject>() {
			@Override
			protected boolean doSelect(Store<BusiObject> store,
					BusiObject parent, BusiObject record, String property,
					String filter) {
				String name = record.get("bname");
				if (name != null) {
					name = name.toLowerCase();
					if (name.indexOf(filter.toLowerCase()) != -1) {
						return true;
					}
				}
				return false;
			}

			@Override
			protected void onFilter() {
				super.onFilter();
			}

		};
		field.bind(getGroupStore());
		initWidget();
	}
	
	private void initWidget(){
		btnQuery = new Button("查询");
		startDate = new DateField();                //Query time
		endDate = new DateField(); 
		btnQuery.addListener(Events.Select, getListener());
		
		initInnerToolBar();
	}
	
	private void initInnerToolBar(){
		HorizontalPanel hp1 = new HorizontalPanel();
		HorizontalPanel hp4 = new HorizontalPanel();
		VerticalPanel vpanel = new VerticalPanel();
		
		FieldSet fs = new FieldSet();
		fs.setHeading("查询操作");
		hp1.add(new LabelField("查询年度从："));
		startDate.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy"));  
		startDate.setWidth(125);
		endDate.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy"));  
		endDate.setWidth(125);
		hp1.add(startDate);
		hp1.add(new LabelField("到："));
		hp1.add(endDate);
		hp1.add(btnQuery);
		
		fs.add(hp1);
		hp4.setSpacing(3);
		vpanel.add(fs);
		vpanel.add(hp4);

		vpanel.setSpacing(3);
		vpanel.add(createGrid());
    	this.setLayout(new FitLayout());
		this.add(vpanel);
	}
	
	BaseStore<BusiObject> getGroupStore() {
		if (store == null) {
			createGroupStore();
		}
		return store;
	}

	BaseStore<BusiObject> createGroupStore() {
		ModelType type_m = new ModelType();
		type_m.setRoot("records");
		type_m.setRecordName("record");
		type_m.setTotalName("totle");
		type_m.addField("remainingVacationDates");
		type_m.getField("remainingVacationDates").setType(Integer.class);
		type_m.addField("departmentName");
		type_m.getField("departmentName").setType(String.class);
		type_m.addField("bname");
		type_m.getField("bname").setType(String.class);
		type_m.addField("years");
		type_m.getField("years").setType(String.class);
		type_m.addField("subsectorName");
		type_m.getField("subsectorName").setType(String.class);
		type_m.addField("entrydate");
		type_m.getField("entrydate").setType(Date.class);
		type_m.addField("indate");
		type_m.getField("indate").setType(Date.class);
		type_m.addField("thisDate");
		type_m.getField("thisDate").setType(Date.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("prolongYearVacationRequest");
		info.setForcenolimit("true");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from prolongYearVacationRequest where 1=2");// 初始化的时候只显示当前月份的数据

		store = new BaseStore<BusiObject>(type_m, info);
		return store;
	}
	
	private BaseGrid<BusiObject> createGrid(){
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();  

		ColumnConfig C2 = new ColumnConfig("departmentName","部门",80);
		columns.add(C2);
		
		ColumnConfig C3 = new ColumnConfig("subsectorName", "分部", 80);
		columns.add(C3);
		
		ColumnConfig C4 = new ColumnConfig("bname", "中文姓名", 80);
		columns.add(C4);
		
		ColumnConfig C5 = new ColumnConfig("entrydate", "入职日期", 100);
		C5.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C5);
		
		ColumnConfig C6 = new ColumnConfig("years", "年度", 80);
		columns.add(C6);
		
		ColumnConfig C7 = new ColumnConfig("remainingVacationDates", "年假天数", 60);
		columns.add(C7);
		
		ColumnConfig C8 = new ColumnConfig("indate", "年假有效期", 100);
		C8.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C8);
		
		ColumnConfig C9 = new ColumnConfig("thisDate", "延长年假到", 100);
		C9.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C9);
		
		ColumnModel cm = new ColumnModel(columns);
		
	   grid = new BaseGrid<BusiObject>(getGroupStore(), cm, false, false);  
	   grid.setBorders(true);  
	   grid.getView().setShowDirtyCells(false);
	   grid.setSize(920,350);
	   return grid ;
	}
	
	int sync = 0;
	Listener<BaseEvent> defaultlistener;
	String startYear = "";
	String endYear = "";
	
	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							startYear = startDate.getRawValue();
							endYear = endDate.getRawValue();
							
							if (startYear.equals("") && endYear.equals("")) {
								MessageBox.alert("提示", "请填写正确的时间段，谢谢", null);
								return;
							}
							if (Integer.parseInt(startYear) >= Integer.parseInt(endYear)) {
								MessageBox.alert("提示", "开始年度必须小于结束年度，请重新选择，谢谢", null);
								return;
							}
							
						    searchRemainingDatesOfYearHoliday();
						}
					}
				}
				 finally {
					sync--;
				}
			}
		};
		return defaultlistener;
	}
	
	private static VacationConverter converter = VacationConverter.getConverter();
	
	private void searchRemainingDatesOfYearHoliday() {
		String getDeductionSalarySql = "select dateTest from hr_Attendance_vacationManagement where holidayCode = 'AL' and isnull(dateTest, '') != ''";
		
		final GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.getDataSet(getDeductionSalarySql, new AsyncCallback<DataSet>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(DataSet result) {
				if (result.getRowCount() == 0 || result.getValue(0, "dateTest").equals("")) {
					MessageBox.alert("提示", "没有相应的年假的假期放假条件，请填写记录，谢谢", null);
					return;
				} else {
					String dateTest = result.getValue(0, "dateTest");
					String countRemainingVacationDatesSql = getCountRemainingVacationDatesSql(dateTest);
					System.out.println(countRemainingVacationDatesSql);
					store.getStoreinfo().setSql(countRemainingVacationDatesSql);
					store.reload();
				}
			}
		});
	}
	
	private String getCountRemainingVacationDatesSql(String dateTest) {
		StringBuilder sql = new StringBuilder();
		sql.append("select case ");
		sql.append(converter.convert(dateTest));
		sql.append(" end - isnull(dates,0) as remainingVacationDates, departmentName,subsectorName, cast(");
		sql.append(startYear);
		sql.append(" - 1 as varchar(4)) %2B '-' %2B cast(");
		sql.append(startYear);
		sql.append(" as varchar(4)) as years,entrydate,indate,bname, thisDate ");
		sql.append("from ");
		sql.append("(select ");
		sql.append("datediff(yy, entrydate, ' ");
		sql.append(startYear);
		sql.append("' %2B '-01-01') as work_experience, ");
		sql.append("(select name from systeminfo where id = up_department) as departmentName, ");
		sql.append("(select name from systeminfo where id = systemid) as subsectorName, ");
		sql.append("entrydate, dateadd(d, -1,' ");
		sql.append(endYear);
		sql.append("' %2B substring(convert(varchar(10),entrydate,120),5,6)) as indate,bcode.bname,bcode.bcode ");
		sql.append("from bcode_job, bcode ");
		sql.append("where bcode_job.bcode = bcode.bcode and employstatus = '在职' and entrydate < '");
		sql.append(endYear);
		sql.append("' %2B '-01-01' ");
		sql.append(") as work_experience ");
		sql.append("left join ");
		sql.append("(select count(1) as dates, bcode_job.bcode, thisDate from ");
		sql.append("vacationDetail inner join ");
		sql.append("bcode_job on bcode_job.bcode = vacationDetail.bcode left join ");
		sql.append("(select year, bcode, requestProlongDate as thisDate from ");
		sql.append("prolongYearVacationRequest where year = '");
		sql.append(endYear);
		sql.append("') as this on this.bcode = bcode_job.bcode left join ");
		sql.append("(select year, bcode, requestProlongDate as lastDate from ");
		sql.append("prolongYearVacationRequest where year = '");
		sql.append(startYear);
		sql.append("') as last on last.bcode = bcode_job.bcode ");
		sql.append("where vacationday between case when lastDate is null then '");
		sql.append(startYear);
		sql.append("' %2B substring(convert(varchar(10),entrydate,120),5,6) ");
		sql.append("else dateadd(dd, 1, lastDate) end and case when thisDate is null then '");
		sql.append(endYear);
		sql.append("' %2B substring(convert(varchar(10),dateadd(dd, -1, entrydate),120),5,6) ");
		sql.append("else thisDate end group by bcode_job.bcode, thisdate ");
		sql.append(") as vacationDates on vacationDates.bcode = work_experience.bcode ");

		return sql.toString();
	}
}